<template>
  <div class="character-manager">
    <div class="header-actions">
      <el-button
        type="primary"
        @click="handleAdd"
      >
        添加角色
      </el-button>
    </div>

    <div class="character-grid">
      <div
        v-for="character in characters"
        :key="character.id"
        class="character-card"
      >
        <div class="character-content">
          <h3>{{ character.name }}</h3>
          <p class="character-desc">{{ character.description }}</p>
          <div class="character-gender">
            <el-tag
              :type="character.gender === 'male' ? 'primary' : character.gender === 'female' ? 'danger' : 'info'"
              size="small"
            >
              {{ character.gender === 'male' ? '男' : character.gender === 'female' ? '女' : '其他' }}
            </el-tag>
          </div>
          <div class="character-tags">
            <el-tag
              v-for="tag in character.tags"
              :key="tag"
              size="small"
              class="tag"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div class="character-actions">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="handleEdit(character)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(character)"
          />
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="description"
        >
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item
          label="性别"
          prop="gender"
        >
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { characterApi } from '@/services/character'

interface Character {
  id: string
  name: string
  description: string
  gender?: 'male' | 'female' | 'other'
}

const characters = ref<Character[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

const form = ref<Character>({
  id: '',
  name: '',
  description: '',
  gender: 'male' // 默认为男性
})

const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择角色性别', trigger: 'change' }]
}

// 加载角色列表
const loadCharacters = async () => {
  loading.value = true
  try {
    const response = await characterApi.initCharacters()
    characters.value = Array.isArray(response) ? response : []
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 添加角色
const handleAdd = () => {
  isEdit.value = false
  form.value = {
    id: crypto.randomUUID(),
    name: '',
    description: '',
    gender: 'male' // 默认为男性
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: Character) => {
  isEdit.value = true
  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row: Character) => {
  try {
    await ElMessageBox.confirm('确定要删除这个角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await characterApi.delCharacter(row.id)
    ElMessage.success('删除成功')
    await loadCharacters()
  } catch (error) {
    if (error instanceof Error && error.message === 'cancel') {
      return
    }
    console.error('删除角色失败:', error)
    ElMessage.error('删除角色失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      // 获取当前角色列表
      const currentCharacters = [...characters.value]

      if (isEdit.value) {
        // 编辑模式：更新现有角色
        const index = currentCharacters.findIndex((c) => c.id === form.value.id)
        if (index !== -1) {
          currentCharacters[index] = form.value
        }
      } else {
        // 添加模式：添加新角色
        currentCharacters.push(form.value)
      }

      // 保存到服务器
      await characterApi.saveCharacter(currentCharacters)

      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      dialogVisible.value = false
      await loadCharacters()
    } catch (error) {
      console.error('保存角色失败:', error)
      ElMessage.error('保存角色失败')
    } finally {
      submitting.value = false
    }
  })
}

// 组件挂载时加载角色列表
onMounted(() => {
  loadCharacters()
})
</script>

<style scoped>
.character-manager {
  padding: 1rem;
}

.header-actions {
  margin-bottom: 1rem;
  display: flex;
  justify-content: flex-end;
}

.character-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.character-card {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.character-content {
  flex: 1;
}

.character-content h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.1rem;
  color: #303133;
}

.character-desc {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0 0 0.5rem 0;
  font-size: 0.9rem;
  color: #606266;
  line-height: 1.5;
  max-height: 3em;
}

.character-tags {
  margin-top: 0.5rem;
}

.character-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>
